import { useUserStore } from '@/stores'
import { createWebHashHistory } from 'vue-router'
import { createRouter } from 'vue-router'
const LoginView = () => import('@/views/login/index.vue')
const LayoutContainer = () => import('@/views/layout/index.vue')
const ArticleManage = () => import('@/views/article/ManagerView.vue')
const ChannelView = () => import('@/views/article/ChannelView.vue')
const ProfileView = () => import('@/views/user/ProfileView.vue')
const AvatarView = () => import('@/views/user/AvatarView.vue')
const PasswordView = () => import('@/views/user/PasswordView.vue')

// createRouter 创建路由实例
// 配置history模式
// 1、history模式 createWebHistory
// 2、hash模式：createWebHashHistory
const router = createRouter({
  // 在vite.config.js中配置
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    // 删掉了为了方便实现注册登录而写的路由
    {
      path: '/',
      component: LayoutContainer,
      redirect: '/article/channel',
      children: [
        { path: '/article/manage', component: ArticleManage },
        { path: '/article/channel', component: ChannelView },
        { path: '/user/profile', component: ProfileView },
        { path: '/user/avatar', component: AvatarView },
        { path: '/user/password', component: PasswordView }
      ]
    },
    { path: '/login', component: LoginView } //登录页
  ]
})

// const whiteList = ['/login']

//登录访问拦截 => 默认是直接放行的
//根据返回值决定，是放行还是拦截
//返回值:
//  1.undefined/true 直接放行
//  2.false 拦回from的地址页面
//  3.具体路径或路径对象拦截到对应的地址

router.beforeEach((to) => {
  // if (whiteList.includes(to.path)) {
  // }
  const userStore = useUserStore()
  // 如果没有token，且访问的是非登录页，拦截到登录，其他情况正常放行,默认是true
  if (!userStore.token && to.path !== '/login') return '/login'
})

export default router
